package com.hitqz.robot.biz.service.impl;

import com.hitqz.robot.api.business.enums.WorkStatusEnum;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.biz.service.AreaActionStrategy;
import com.hitqz.robot.biz.service.BusinessService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.driver.model.IRobotPosDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author xupkun
 * @date 2024/8/19
 */
@Service("charging")
@RequiredArgsConstructor
@Slf4j
public class ChargeServiceImpl implements AreaActionStrategy {

    private final BusinessService businessService;

    private final RobotDriverService robotDriverService;

    private final RobotService robotService;



    @Override
    public int doActionAnyWhere(double distance, String params) {
        try {
            businessService.goCharge(false, false);

            IRobotPosDto iRobotPosDto = robotDriverService.getWebPos();
            Robot robot = robotService.getDefaultRobot();

            if (robot == null) {
                log.error("Default robot is null.");
                return 0;
            }

            if (iRobotPosDto != null) {
                updateRobotStatusBasedOnPosition(iRobotPosDto, robot);
            }

        } catch (Exception e) {
            log.error("Error occurred during charge task: ", e);
        }
        return 1;
    }

    @Override
    public int doActionInArea(double distance, String params) {

        return 0;
    }

    @Override
    public int doActionEnterArea(double distance, String params) {




        return 0;
    }

    @Override
    public int doActionLeaveArea(double distance, String params) {
        return 0;
    }


    private void updateRobotStatusBasedOnPosition(IRobotPosDto iRobotPosDto, Robot robot) {
        if (iRobotPosDto.getBatteryLevel() >= 50.0) {
            if (Objects.equals(robot.getWorkStatus(), WorkStatusEnum.CHARGE.getCode())) {
                log.info("Battery level exceeded threshold, canceling charging.");
                robot.setWorkStatus(WorkStatusEnum.FREE.getCode());
                robotService.updateById(robot);
            }
        } else {
            if (iRobotPosDto.isCharging() && !Objects.equals(robot.getWorkStatus(), WorkStatusEnum.CHARGE.getCode())) {
                log.info("Current is positive, changing to charging status.");
                robot.setWorkStatus(WorkStatusEnum.CHARGE.getCode());
                robotService.updateById(robot);
            }
        }

    }

}
